#THIS IS A PROGRAM FOR UPDATING SWITCHER
import os
import requests
from tqdm import tqdm
import os.path as op
import urllib.request
import zipfile
import shutil

try:
    curl = 'https://gitee.com/summer-uefi/software-problem-feedback/raw/master/update_link.html'
    zzk = urllib.request.urlopen(curl)
except:
    print("网络错误")
    exit()
else:
    print("正在获取下载地址......")

url = zzk.read().decode('utf-8')
print("获取成功！")
print('正在下载......')
filename = 'updatepkg'

"""
url: 文件地址
filename: 保存文件命名, 保存在当前目录
"""
def downloadfile(url, filename):
    filename = filename  + op.splitext(url)[-1]
    file_to_save = op.join(os.getcwd(), filename)  #获取当前路径

    response = requests.get(url, stream=True)
    with open(file_to_save, "wb") as f:
        for data in tqdm(response.iter_content(chunk_size=1024)):
            f.write(data)

if __name__ == "__main__":
    print("d")
    #downloadfile(url,filename)

nowpth = os.getcwd()
try:
    os.system('cd backup')
except:
    print('2')
else:
    os.system('rmdir backup /s /q')
# 移动目标文件夹的根目录
movabs_path = nowpth + "/backup"
# 移动文件夹的根目录
rawabs_path = nowpth + "/main"
# 移动操作
shutil.copytree(rawabs_path,movabs_path)
#删除操作
os.system('rmdir main /s /q')

src_path = nowpth + '\\updatepkg.zip'
target_path = nowpth + '\\main'
if (not os.path.isdir(target_path)):
    z = zipfile.ZipFile(src_path, 'r')
    z.extractall(path=target_path)
    z.close()
